﻿using System;
using System.Linq;

namespace Rosetta.Composition
{
    public sealed class TemplateValidator : SingleNodeVisitor
    {
        // TODO: Handle recursive converter calls

        #region Fields

        private bool result = true;

        #endregion

        #region Constructors

        private TemplateValidator()
        {
        }

        #endregion

        #region Protected Methods

        protected override void Visit(Node node)
        {
            if (node.CanHaveParents)
            {
                if (node.Parents.Count() != node.ArgumentCount)
                {
                    result = false;
                    return;
                }
            }

            if (node.CanHaveChildren)
            {
                var children = node.Children.ToArray();

                if (children.Length == 0)
                {
                    result = false;
                }
                else
                {
                    // Visit children
                    foreach (var child in children.Select(nc => nc.EndPoint))
                    {
                        child.Accept(this);
                    }
                }
            }
        }

        #endregion

        #region Class Methods

        /// <summary>
        /// Returns true if the complete template tree is connected.
        /// </summary>
        public static bool IsComplete([NotNull] Template template)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            var visitor = new TemplateValidator();
            template.Accept(visitor);
            return visitor.result;
        }

        #endregion
    }
}